#!/usr/bin/env python
# encoding: utf-8


"""
@file: qiubudengshibiaodashi.py
@time: 2017/5/11 上午11:43
"""
# 求不等式表达式
# 已知解集求不等式表达式

from mathsolver.functions.base import *
from mathsolver.functions.budengshi import common_opers as co


# 求不等式表达式
# style1 Input paramer1:(f(x) > 0 形式); paramer2: BaseInter解集 ouput 不等式组
class QiuBuDengShiBiaoDaShi(BaseFunction):
    def solver(self, *args):
        self.label.add('一元二次不等式解集表示不等式')
        arg1, arg2 = args
        ineq = co.to_ineq_expr_list(str(arg1.sympify()))
        fx, ineq_op, r = ineq
        if isinstance(arg2, BaseInter):
            ineq_set = arg2.interval
        elif isinstance(arg2, BaseInnerSet):
            ineq_set = arg2.value['value']
        else:
            ineq_set = arg2
        self.steps.append(['因为' + arg1.printing() + '解集为:', new_latex(ineq_set)])
        _x = sympify('x')
        _a = sympify('a')
        if isinstance(ineq_set, Interval):
            v1 = ineq_set.left
            v2 = ineq_set.right
            new_f = _a * (_x - v1) * (_x - v2)
            if ineq_op.find('>') >= 0:
                _a_v = -1
            else:
                _a_v = 1
        elif isinstance(ineq_set, Union):
            set1, set2 = ineq_set.args
            v1 = set1.right
            v2 = set2.left
            new_f = _a * (_x - v1) * (_x - v2)
            if ineq_op.find('>') >= 0:
                _a_v = 1
            else:
                _a_v = -1
        else:
            raise Exception('Illegal parameter')
        fx_expr = new_f.subs(_a, _a_v)
        new_ineq = BaseIneq([fx_expr, ineq_op, r])
        self.steps.append(['所以原不等式可表示为:', new_ineq.printing()])
        self.output.append(BaseSymbolValue({fx: fx_expr}))
        return self


if __name__ == '__main__':

    _solve = QiuBuDengShiBiaoDaShi().solver(BaseExpression('f(x)<0'),
                                            BaseInnerSet({'var': 'x', 'domain': 'R', 'name': '',
                                                          'value': Interval(-S.Infinity, -1).union(
                                                              Interval(sympify('1/2'), S.Infinity))}))
    # intl = co.to_base_interval(Interval(-S.Infinity, -1).union(Interval(sympify('1/2'), S.Infinity)))
    # _solve = QiuBuDengShiBiaoDaShi().solver(BaseIneq(['f(x)', '<', '0']), intl)
